package com.buka.recipe.security.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.buka.recipe.common.result.ResultGenerator;
import com.buka.recipe.system.service.LoginLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 */
@Log4j2
@Component
public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final LoginLogService loginLogService;

    @Autowired
    public JsonAuthenticationSuccessHandler(LoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 保存日志
        loginLogService.save(request, true, "登录成功");

        log.info("登录成功, {}", authentication.getName());
        JSONObject details = JSONObject.from(authentication.getDetails());
        String sessionId = details.getString("sessionId");
        Map<String, String> result = new HashMap<>(1);
        result.put("token", sessionId);
        response.getWriter().write(JSON.toJSONString(ResultGenerator.genSuccessResult(result)));
    }
}
